package com.redxiii.safesync;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CryptoToolWithGZip extends CryptoToolBase implements CryptoTool {

	private static final Logger logger = LoggerFactory.getLogger(CryptoToolWithGZip.class);
	
	public CryptoToolWithGZip(String passPhrase) {
		super(passPhrase);
	}
	
	/* (non-Javadoc)
	 * @see com.redxiii.safesync.CryptoTool#encrypt(java.io.InputStream, java.io.OutputStream)
	 */
	public void encrypt(InputStream inStream, OutputStream outStream) throws IOException {
		
		int count = 0;
		byte[] rawData = new byte[bufferSize];
		
		CipherOutputStream cipherStream = new CipherOutputStream(outStream, ecipher);	// Thanks to L.Lima
		GZIPOutputStream zipStream = new GZIPOutputStream(cipherStream);
		
		logger.trace("Reading {} bytes ...", inStream.available());
		while ((count = inStream.read(rawData)) != -1) {
			zipStream.write(rawData, 0, count);
		}
		zipStream.flush();
		zipStream.close();
		
	}
		
	/* (non-Javadoc)
	 * @see com.redxiii.safesync.CryptoTool#decrypt(java.io.InputStream, java.io.OutputStream)
	 */
	public void decrypt(InputStream inStream, OutputStream outStream) throws IOException {
		
		int count;
		byte[] safeData = new byte[bufferSize];
		
		CipherInputStream cipherStream = new CipherInputStream(inStream, dcipher);	// Thanks to L.Lima
		GZIPInputStream zipStream = new GZIPInputStream(cipherStream);
		
		logger.trace("Reading, Decrypting and Uncompressing ...");
		while ((count = zipStream.read(safeData)) != -1) {
			logger.trace("Read {} bytes...", count);
			outStream.write(safeData, 0, count);
		}
		outStream.flush();
		outStream.close();
	}
}